package com.zhx.real.security.validate.code.impl;


import com.zhx.real.common.ValidateCodeType;
import com.zhx.real.security.validate.code.ValidateCode;
import com.zhx.real.security.validate.code.ValidateCodeGenerator;
import com.zhx.real.security.validate.code.ValidateCodeProcessor;
import com.zhx.real.security.validate.code.ValidateCodeRepository;
import com.zhx.real.util.exception.ValidateCodeException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.Map;

/**
 * 一个ValidateCodeProcessor 的抽象实现类
 * @author zhanghaixuan
 * 2017年11月04日16:11:13
 */
public abstract class AbstractValidateCodeProcessor<C extends ValidateCode> implements ValidateCodeProcessor {
    /**
     * 收集系统中所有 ValidateCodeGenerator 接口的实现
     */
    @Autowired
    private Map<String, ValidateCodeGenerator> validateCodeGeneratorMap;


    @Autowired
    private ValidateCodeRepository validateCodeRepository;


    /**
     * 生成校验码
     * @param request
     * @throws Exception
     */
    @Override
    public void create(ServletWebRequest request) throws Exception {
        C validateCode = generate(request);
        save(request,validateCode);
        send(request,validateCode);
    }

    /**
     * 生成校验码的封装
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    private C generate(ServletWebRequest request){
        //获取请求的校验码类型
        String type = getProcessorType(request);
        //从spring帮忙注入的map中去查找当前校验码的生成实现
        ValidateCodeGenerator validateCodeGenerator = validateCodeGeneratorMap.get(type+"CodeGenerator");
        return (C) validateCodeGenerator.generate(request);
    }

    /**
     * 保存校验码到session中去
     * @param request
     * @param validateCode
     */
    private void save(ServletWebRequest request, ValidateCode validateCode){
        ValidateCode code = new ValidateCode(validateCode.getCode(),validateCode.getLocalDateTime());

        validateCodeRepository.save(request, code, getValidateCodeType(request));
    }

    /**
     * 提供一个抽象的方法给子类去重写自己的发送校验码的逻辑 由子类实现
     * @param request
     * @param validateCode
     * @throws Exception
     */
    protected abstract void send(ServletWebRequest request, C validateCode) throws Exception;




    /**
     * 获取请求的校验码类型  全局统一 为 image smsCode
     * @param request
     * @return
     */
    private String getProcessorType(ServletWebRequest request){
        return StringUtils.substringAfter(request.getRequest().getRequestURI(),"/code/");
    }

    /**
     * 构建验证码放入session时的key
     *
     * @param request
     * @return
     */
    private String getSessionKey(ServletWebRequest request) {
        return SESSION_KEY_PREFIX + getValidateCodeType(request).toString().toUpperCase();
    }

    /**
     * 根据请求的url获取校验码的类型
     *
     * @param request
     * @return
     */
    private ValidateCodeType getValidateCodeType(ServletWebRequest request) {
        String type = StringUtils.substringBefore(getClass().getSimpleName(), "CodeProcessor");
        return ValidateCodeType.valueOf(type.toUpperCase());
    }


    @SuppressWarnings("unchecked")
    @Override
    public void validate(ServletWebRequest request) {

        ValidateCodeType processorType = getValidateCodeType(request);
        String sessionKey = getSessionKey(request);

        C codeInSession = (C) validateCodeRepository.get(request, processorType);

        String codeInRequest;
        try {
            codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),
                    processorType.getParamNameOnValidate());
        } catch (ServletRequestBindingException e) {
            throw new ValidateCodeException("获取验证码的值失败");
        }

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException(processorType + "验证码的值不能为空");
        }
        if (codeInSession == null) {
            throw new ValidateCodeException("验证码不存在");
        }

        if (codeInSession.isExpried()) {
            validateCodeRepository.remove(request, processorType);
            throw new ValidateCodeException("验证码已过期");
        }

        if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException("验证码不匹配");
        }

        validateCodeRepository.remove(request, processorType);
    }


}
